package com.mldong.wxauth.interceptor;

import cn.hutool.core.util.StrUtil;
import com.mldong.wxauth.token.ITokenStore;
import com.mldong.wxauth.tool.AssertTool;
import com.mldong.wxauth.vo.TokenVO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    final static String TOKEN_KEY = "token";
    private ITokenStore tokenStore;

    public LoginInterceptor(ITokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        if(StrUtil.isEmpty(token)) {
            AssertTool.throwBiz("token不能为空");
        }
        TokenVO tokenVO = tokenStore.get(token);
        if(tokenVO == null) {
            AssertTool.throwBiz("token不存在或过期");
        }
        return true;
    }
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_KEY);
        if(StrUtil.isEmpty(token)) {
            token = request.getParameter(TOKEN_KEY);
        }
        return token;
    }
}
